package godlike.tech.websocket1.controller;

import godlike.tech.websocket1.model.Chat;
import godlike.tech.websocket1.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

@Controller
public class GreetingController {
//    @MessageMapping("/hello")
//    @SendTo("/topic/greetings")
//    public Message greeting(Message message) {
//
//        System.out.println(message.getName());
//        System.out.println(message.getContent());
//        return message;
//    }

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;

    // <<< /app/hello
    @MessageMapping("/hello")
    public void greeting(Message message) {
        System.out.println(message.getName());
        System.out.println(message.getContent());
        // >>> /topick/greetings
        simpMessagingTemplate.convertAndSend("/topic/greetings", message);
    }


    // <<< /app/p2p
    @MessageMapping("/p2p")
    public void chat(Principal principal, Chat chat) {

        chat.setFrom(principal.getName());

        // >>> /user/queue/p2p
        simpMessagingTemplate.convertAndSendToUser(chat.getTo(), "/queue/p2p", chat);
    }


}
